package ch06.shizhang;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 茜茜
 * @date 2024-11-23 11:23
 */
public class convert {
    public static <T> T convertToPojo(Map<String, String[]> parameterMap, Class<T> clazz) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        T t = clazz.newInstance();

        // 从request中获取参数并赋值给实例对象
        for (String key : parameterMap.keySet()) {
            try {
                Method method = clazz.getMethod("set" + capitalize(key), String.class);
                String value = parameterMap.get(key)[0];
                method.invoke(t, value);
            } catch (NoSuchMethodException e) {
                System.out.println("No such method: " + key);
            }
        }

        return t;
    }


    private static String capitalize(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }



    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        Map<String, String[]> parameterMap = new HashMap<>();
        parameterMap.put("realname", new String[]{"张三"});
        parameterMap.put("age", new String[]{"25"});
        parameterMap.put("email", new String[]{"zhangsan@example.com"});

        User user = convertToPojo(parameterMap, User.class);

        System.out.println(user.getRealname());
        System.out.println(user.getAge());
        System.out.println(user.getEmail());
    }
}
